package main

import (
	"context"
	"fmt"
	"os"
	"path"
	"strings"
	"time"
)

func StartDelTimer(ctx context.Context) {
	scan := time.NewTicker(time.Hour)
	ScanRoot(rootDir)
	fmt.Println("end")
	for {
		select {
		case <-scan.C:
			ScanRoot(rootDir)
		case <-ctx.Done():
			break
		}
	}
}

func ScanRoot(rootDir string) {
	ids := GetIPCIds(rootDir)
	for _, id := range ids {
		subdir := path.Join(rootDir, id)
		ScanAndDelMp4(subdir)
	}
}
func ScanAndDelMp4(folder string) {
	entrys, err := os.ReadDir(folder)
	if err != nil {
		fmt.Println(err)
		return
	}
	expireTime := time.Now().AddDate(0, 0, -8)
	for _, entry := range entrys {
		if entry.IsDir() {
			continue
		}
		baseName := entry.Name()
		if strings.HasPrefix(baseName, ".") {
			continue
		}
		if !strings.HasSuffix(baseName, ".mp4") {
			continue
		}
		timeStr := baseName[:len(baseName)-4]
		formatStr := "20060102150405"
		t, errParse := time.Parse(formatStr, timeStr)
		if errParse != nil {
			fmt.Println("转换失败:", errParse)
			return
		}
		if t.Before(expireTime) {
			fmt.Println("to del ", path.Join(folder, entry.Name()))
			os.Remove(path.Join(folder, entry.Name()))
		}
	}
}
